/* global AMap */
import React, { useEffect, useRef, useState } from 'react'
import styles from '../index.module.less';
import _cloneDeep from 'lodash/cloneDeep';

export default function Map(props) {
    const [map, setMap] = useState();
    const [overlay, setOverlay] = useState();
    const earthLayer = useRef(new AMap.TileLayer.Satellite());
    useEffect(() => {
        initMap();
    }, []);
    useEffect(() => {
        if (props.overlayVisible && map) {
            addOverlay(map);
        } else {
            map && map.remove(overlay);
        }
    }, [props.overlayVisible]);
    useEffect(() => {
        if (props.earthVisible) {
            map && map.add(earthLayer.current);
        }
        else {
            map && map.remove(earthLayer.current);
        }
    }, [props.earthVisible]);

    function addOverlay(map) {
        const polygon = new AMap.Polygon({
            path: _cloneDeep(props.coordinates),
            strokeColor: "#FF33FF", 
            strokeWeight: 6,
            strokeOpacity: 0.2,
            fillOpacity: 0.4,
            fillColor: '#1791fc',
            zIndex: 50,
        })
        map.add(polygon);
        setOverlay(polygon);
    }

    function initMap() {
        const map = new AMap.Map('amap', {
            resizeEnable: true,
            zoom: 8,
            center: [116.397428, 39.90923],
            viewMode: '3D'
        });
        map.plugin(['AMap.ToolBar'],function(){
            //加载工具条
            var tool = new AMap.ToolBar();
            map.addControl(tool);    
        });
        setMap(map);
        props.overlayVisible && addOverlay(map);
    }

    return (
        <div id="amap" className={styles.amap}></div>
    )
}
